﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Input;
using System.Collections.ObjectModel;
using System.Collections;

namespace AliyunMobileTestTechnology.ViewModel.Commands
{
    class StopCollectCovCommand : ICommand
    {
        private WorkPlatformViewModel workPlatformViewModel;
        public StopCollectCovCommand(WorkPlatformViewModel workPlatformViewModel)
        {
            this.workPlatformViewModel = workPlatformViewModel;
        }

        public bool CanExecute(object parameter)
        {
            return true;
        }

        public event EventHandler CanExecuteChanged;

        public void Execute(object parameter)
        {


            IList modules = parameter as IList;

            List<string> cmdList = new List<string>();
            if (modules.Count != 0)
            {
                #region dump coverage
                Module module = (Module)modules[0];
                if (module.Name == "All")
                {
                    cmdList.Add("adb shell am broadcast -a aliyun.intent.action.dumpcoverage");
                }
                else
                {
                    foreach (string packagename in module.Packages)
                    {
                        cmdList.Add("adb shell am broadcast -e packagename " + packagename + " -a aliyun.intent.action.dumpcoveragebyname");
                    }
                }
                foreach (string cmd in cmdList)
                {
                    WorkPlatformViewModel.ExecuteCommand(cmd);
                }
                #endregion

                #region pull file
                string localPath = SettingsViewModel.WorkSpaceConfigValue;
                foreach (string packagename in module.Packages)
                {
                    foreach (string app in module.APPs)
                    {
                        pullFile(packagename, localPath + "trunk/TestResults/" + app);
                    }
                }
                #endregion
            }




            workPlatformViewModel.ListViewIsEnable = true;
        }

        public void pullFile(string package, string destination)
        {
            //todo
            string source = string.Format("/data/data/{0}/files/coverage.ec");

            string cmd = string.Format("adb pull {0} {1}", package, destination);
            string output = WorkPlatformViewModel.ExecuteCommand(cmd);

            if (!output.Contains("bytes in"))
            {
                throw new ArgumentException(output);
            }

        }
    }
}
